package slave;

import java.io.*;
import java.net.*;

import util.Criptografia;
class Slave implements Runnable {
	public static final String MASTER_HOST = "127.0.0.1";
	public static final int MASTER_PORT = 6789;
	
	public static void main(String argv[]) throws Exception
	{
		Slave slave = new Slave();
		slave.run();
	}

	@Override
	public void run() {
		MasterChannel channel = null;
		System.out.print("Trying to connect to master...");
		try {
			channel = MasterChannel.connect(Slave.MASTER_HOST, Slave.MASTER_PORT);
			System.out.println("connected");
		} catch (UnknownHostException e) {
			System.out.println("unknown host");
			return;
		} catch (IOException e) {
			System.out.println(e.getMessage());
			return;
		}
				
		try {
			while (true) {
				System.out.print("Awaiting call...");
				MasterChannelCall call = channel.awaitCall();
				System.out.println("received call for " + call.getOperation());
				
				if (call.getOperation().equalsIgnoreCase("decifrarTexto")) {
					String result = Criptografia.decifra(call.getParams()[0], call.getParams()[1]);

					if(!result.contains(call.getParams()[2])){
						result = null;
					}
					
					call.returns(result);
				}
				else {
					System.out.println("Ignored operation!");
				}
			}
		} catch (IOException e) {
			System.out.println("exiting");
			return;
		}
	}
}